//
//  CComposedUrl.m
//  IconMaster
//
//  Created by 为为 on 13-5-19.
//  Copyright (c) 2013年 为为. All rights reserved.
//

#import "CComposedUrl.h"

@implementation CComposedUrl

- (id)init
{
	return [self initWithString:@""];
}

- (id)initWithString:(NSString *)str
{
	if (self = [super init]) {
		[self parseUrl:str];
	}
	return self;
}

- (void)parseUrl:(NSString*)url
{
	NSError* error;
	NSRegularExpression* regex = [[NSRegularExpression alloc] initWithPattern:@"\\{(.*?):(.*?)\\}" options:0 error:&error];
	NSArray* matches = [regex matchesInString:url options:0 range:NSMakeRange(0, [url length])];
	for (NSTextCheckingResult* match in matches) {
		NSString* key = [url substringWithRange:[match rangeAtIndex:1]];
		NSString* val = [url substringWithRange:[match rangeAtIndex:2]];
		if ([val isEqualToString:@"(null)"]) {
			val = nil;
		}
		if ([key isEqualToString:@"password"]) {
			self.password = val;
		}
		if ([key isEqualToString:@"realUrl"]) {
			self.realUrl = val;
		}
		if ([key isEqualToString:@"title"]) {
			self.title = val;
		}
	}
}

- (NSString *)getString
{
	NSMutableString* string = [[NSMutableString alloc] initWithCapacity:256];
	if (self.password) {
		[string appendFormat:@"{%@:%@}",@"password",self.password];
	}
	if (self.realUrl) {
		[string appendFormat:@"{%@:%@}",@"realUrl",self.realUrl];
	}
	if (self.title) {
		[string appendFormat:@"{%@:%@}",@"title",self.title];
	}
	
	return string;
}

@end
